package au.org.tern.ecoinformatics.oai.provider;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

/**
 * Adds the default + an optional environmental specific properties file to Spring's {@link PropertyPlaceholderConfigurer}.
 */
public class EnvironmentalPropertyConfigurer extends PropertyPlaceholderConfigurer {
	static final Logger LOG = Logger.getLogger(EnvironmentalPropertyConfigurer.class);

	public EnvironmentalPropertyConfigurer() {
		ResourceLoader resourceLoader = new DefaultResourceLoader();
		String environmentString = System.getProperty("application.environment");

		if (environmentString != null) {
			LOG.info("Merging/overriding default properties (application.properties file) with environmental properties for \"" + environmentString + "\" file");
			setLocations(new Resource[] { resourceLoader.getResource("classpath:application.properties"),
					resourceLoader.getResource("classpath:" + environmentString + "-application.properties") });
		} else {
			LOG.warn("No application.environment was specified as a JVM property, properties will only be loaded from application.properties file");
			setLocation(resourceLoader.getResource("classpath:application.properties"));
		}
	}
}